home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus 1995 #1 / Amiga Plus 1995 #1.iso / fish-disketten / fish_691-700 / d695 / icalc / scripts / root.ic < prev    next >
Text File  |  1994-12-13  |  559b  |  27 lines

  1. # Newton-Raphson method for root-finding.
  2. #
  3. # example:
  4. # > func f(x) = exp(x) - E        # has root at x = 1
  5. # > nroot(f(x), exp(x), 1.5, 0.01)     # needs derivative
  6. #
  7.  
  8. ROOT_MAXITER = 30
  9.  
  10. # Newton-Raphson method
  11. func nroot(~xexpr,~dxexpr, x1, x2, xacc) = {
  12.     local j, df, dx, f, rtn
  13.  
  14.     rtn = 0.5*(x1+x2)
  15.     for (j = 1; j <= ROOT_MAXITER; j+=1) {
  16.         x = rtn
  17.         f = xexpr    # eval fn at rtn,
  18.         df = dxexpr    # and derivative
  19.         dx = f/df
  20.         rtn -= dx
  21.         if ((x1-rtn)*(rtn-x2) < 0)
  22.             error(0)    # farther away
  23.         if (abs(dx) <= xacc) return rtn
  24.     }
  25.     error(1)    # max iterations reached
  26. }
  27.